<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="com.crm.util.RequestEx"%>
<%@ page import="com.crm.service.KcService"%>
<%@ page import="com.crm.po.Config"%>
<%@ page import="com.crm.util.SESSION"%>
<%@ page import="com.crm.po.Users"%>
<%
	Object obj = request.getSession(true).getAttribute(SESSION.USER_SESSION_KEY);
	Users users = null;
	if(obj != null){
		users = (Users) obj;
	}
	String path = request.getContextPath();
	String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
	KcService service = new KcService();
	
	String taxrate = "";
	
	int kcCount = service.getKcCountByTreeid(treeid, "Y");

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>CRM</title>
    <link rel="icon" mce_href="<%=path%>/images/title_logo.ico" href="<%=path%>/images/title_logo.ico" type="image/x-ico"/>
    <link rel="shortcut icon" mce_href="<%=path%>/images/title_logo.ico" href="<%=path%>/images/title_logo.ico" type="image/x-ico"/>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>	
	<link rel="stylesheet" type="text/css" href="<%=path%>/js/easyui1.3.2/themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="<%=path%>/js/easyui1.3.2/themes/icon.css">	
	<script type="text/javascript" src="<%=path%>/js/easyui1.3.2/jquery-1.8.0.min.js"></script>
	<script type="text/javascript" src="<%=path%>/js/easyui1.3.2/jquery.easyui.min.js"></script>
	<script type="text/javascript" src="<%=path%>/js/easyui1.3.2/locale/easyui-lang-zh_CN.js"></script>
	<script type="text/javascript" src="<%=path%>/js/My97DatePicker/WdatePicker.js"></script>
	<script type="text/javascript" src="<%=path%>/js/math.js"></script>
	<style type="text/css">
		body,td,th,div{
 			font-size:12px;
		}
	</style>
  </head>
  
  <body style="margin:0;padding:0" class="easyui-layout">
    <script type="text/javascript">

	var datagrid;
	var url = "<%=path%>/kc.do";

	//准备新增数据
	function readySave(){
		document.getElementById("saveAndGoon").style.display="inline";
		$('#recSaveOrUpdate').dialog({  
			title: '新增',  
			width: 430,
			height: 220,
			closed: false,  
			cache: false,   
			modal: true,
			onClose:function(){$('#recSaveOrUpdateForm').form('clear');}
		});
	}
	//新增数据
	function doSave(isContinue){		
		$("#recSaveOrUpdateForm").form('submit', { 
	        url: url + '?method=saveOrUpdateKc&treeid=<%=treeid%>',	        
			success:function(data){
				if('ok' == data){
					if(isContinue){
						//$('#recSaveOrUpdateForm').form('clear');
					}else{
						$('#recSaveOrUpdate').dialog('close');
					}					
					datagrid.datagrid('reload');
				}else{
					$.messager.alert('提示', data, 'info');
				}
			},
			error : function() {
			
			}
		});
	}

	//修改数据
	function doUpdate(){
		var node = datagrid.datagrid('getSelected');
		document.getElementById("saveAndGoon").style.display="none";
		$('#recSaveOrUpdate').dialog({  
			title: '修改',  
			width: 430,
			height: 220,
			closed: false,  
			cache: false,   
			modal: true,
			onClose:function(){$('#recSaveOrUpdateForm').form('clear');}
		});
		$('#recSaveOrUpdateForm').form('load',{
			tid: node.tid,
			kcname: node.kcname,		
			price: node.price,
			amount: node.amount,
			totalprice: node.totalprice,
			usercompany: node.usercompany,
			remark: node.remark
		});	
	}

	//删除数据
	function doDelete(){
		var node = datagrid.datagrid('getSelected');
		//删除确认
		$.messager.confirm('提示','<br>您确定删除选中的数据吗?',function(r){ 
			if(r){ 
				//执行删除
				var tids = "'" + node.tid + "'";

				$.ajax({
					url : url + '?method=deleteKc&treeid=<%=treeid%>',
					type : 'POST',
					data : {tids : tids},
					success : function(data, textStatus) {
						if('ok' == data){
							datagrid.datagrid('load');
						}else{								
							$.messager.alert('提示', data, 'info');
						}		
					}
				});
			} 
		});
	}
	//查询
	function doQuery(){
		datagrid.datagrid('options').url = url+'?method=getKcList&treeid=<%=treeid%>&islive=Y';
		var queryParams = datagrid.datagrid('options').queryParams;
		
		if($.trim($("#kcname").val()).length == 0 && 
		   $.trim($('#usercompany').val()).length == 0){
			   
		   	queryParams.kcname = "";
		   	queryParams.usercompany = "";
		}else{
			queryParams.kcname = $("#kcname").val();
			queryParams.usercompany = $('#usercompany').val();
		}
		datagrid.datagrid('load');
	}
	
	//定义datagrid列模型
	var columns = [[
		{field:'ck',checkbox:true},        	
		{field:'oper',title:'操作',width:70,formatter:formatOper},
		{field:'tid',title:'主键',width:20,hidden:true},
		{field:'kcname',title:'库存名称',width:80},
		{field:'price',title:'单价',width:80,formatter:formatPrice,sortable:true},
		{field:'amount',title:'数量',width:60},
		{field:'totalprice',title:'合计金额',width:80,formatter:formatPrice,sortable:true},
		{field:'usercompany',title:'使用客户',width:180},
		{field:'remark',title:'备注',width:150},
		{field:'creattime',title:'创建时间',width:115,formatter:formatDate},
		{field:'updatetime',title:'最后修改时间',width:115,formatter:formatDate},
		{field:'creater',title:'创建用户',width:100},
		{field:'updater',title:'最后修改用户',width:100}
	]];

	//入口
	$(function(){
		datagrid = $('#datagrid');
		$(datagrid).datagrid({
			url:url+'?method=getKcList&treeid=<%=treeid%>&islive=Y', 
			toolbar:'#tb',
			columns:columns,
			title:'', 
			loadMsg:'正在处理...',
			iconCls:'', 
			nowrap: true, 
			selectOnCheck: false,
			checkOnSelect: false,
			rownumbers: true,
			remoteSort: false,
			autoRowHeight: false,
			autoRowWidth: true,             
			animate:true, 
			singleSelect: true,
			collapsible: true, 
			fitColumns: false,//自动充满列
			fit:true,//自动充满浏览器区域
			idField:'tid', 
			showFooter: false,
			striped:true,//斑马线
			pagination:true,
			pageSize:50,
			onClickRow:function(rowIndex, rowData){

			},
			onDblClickRow:function(rowIndex, rowData){
				<%
				if(users.getKcAuth().indexOf("AUTH_U") >= 0){
				%>
				doUpdate();
				<%	
				}
				%>				
			},
			onLoadSuccess:function(data){
				var p = datagrid.datagrid('getPager');  
				$(p).pagination({
					buttons : [
								<%if(users.getKcAuth().indexOf("AUTH_J") >= 0){%>
								   {
									text:'计算合计',
									handler:function(){
										sumDatagrid();
									}
								   }
								<%}if(users.getKcAuth().indexOf("AUTH_J") >= 0 && users.getKcAuth().indexOf("AUTH_E") >= 0){%>
								   ,
								<%}if(users.getKcAuth().indexOf("AUTH_E") >= 0){%>
								   {
									text:'导出',
									handler:function(){
										readyExport();
									}
								   }
								<%}%>
								   ],
					pageList:[50, 100, 200, 500, <%=kcCount <= 500 ? "1000" : kcCount + ""%>]
			    });  
			}
		}); 

		
	}); 
	
	function sumDatagrid(){
		var checkedItems = datagrid.datagrid('getChecked');
		
		var amount_sum = '';
		var price_sum = '';
		var totalprice_sum = '';
		
		$.each(checkedItems, function(index, item){
			if(amount_sum.length > 0){amount_sum = amount_sum + '_';}
			if(price_sum.length > 0){price_sum = price_sum + '_';}
			if(totalprice_sum.length > 0){totalprice_sum = totalprice_sum + '_';}

			amount_sum = amount_sum + item.amount;
			price_sum = price_sum + item.price;
			totalprice_sum = totalprice_sum + item.totalprice;
		});

		$.ajax({
			url : url + '?method=mathBatchAdd',
			type : 'POST',
			data : {amount_temp : amount_sum,
					price_temp : price_sum,
					totalprice_temp : totalprice_sum
			},
			success : function(data, textStatus) {
					amount_sum = data.amount_sum;
					price_sum = formatPrice(data.price_sum, null);
					totalprice_sum = formatPrice(data.totalprice_sum, null);
				
					amount_sum = "数量：<span style='font-weight:bold;color:#FF0000;font-size:14px'>" + amount_sum + "</span><span style='color:#FFFFFF;'>__</span>";
					price_sum = "单价：<span style='font-weight:bold;color:#FF0000;font-size:14px'>" + price_sum + "</span><span style='color:#FFFFFF;'>__</span>";
					totalprice_sum = "合计金额：<span style='font-weight:bold;color:#FF0000;font-size:14px'>" + totalprice_sum + "</span><span style='color:#FFFFFF;'>__</span>";
					
					document.getElementById("sumDatagrid").innerHTML = price_sum + amount_sum + totalprice_sum;
			}
		});
	}

	//格式化创建时间
	function formatDate(value, row){
		value = value + '';
		if(value == null || value.length == 0){
			return "";
		}
		var yy = '';
		var mo = '';
		var da = '';
		
		var ho = '';
		var mm = '';
		var ss = '';

		var dateTime = '';
		if(value.length > 4){
			yy = value.substr(0, 4);
			dateTime = dateTime + yy;
		}
		if(value.length > 6){
			mo = value.substr(4, 2);
			dateTime = dateTime + '-' + mo;
		}
		if(value.length > 8){
			da = value.substr(6, 2);
			dateTime = dateTime + '-' + da;
		}
		
		if(value.length > 10){
			ho = value.substr(8, 2);
			dateTime = dateTime + ' ' + ho;
		}
		if(value.length > 12){
			mm = value.substr(10, 2);
			dateTime = dateTime + ':' + mm;
		}
		if(value.length >= 14){
			ss = value.substr(12, 2);
			dateTime = dateTime + ':' + ss;
		}
		return dateTime;
	}

	//格式化操作
	function formatOper(value, row){
		var updateOper = "<font color='#C0C0C0'>修改</font>";
		var deleteOper = "<font color='#C0C0C0'>删除</font>";
		<%
		if(users.getKcAuth().indexOf("AUTH_U") >= 0){
		%>
			updateOper = "<a href='javascript:doUpdate();'>修改</a>";
		<%
		}
		if(users.getKcAuth().indexOf("AUTH_D") >= 0){
		%>
			deleteOper = "<a href='javascript:doDelete();'>删除</a>";
		<%
		}
		%>
		return updateOper + '&nbsp;&nbsp;&nbsp;' + deleteOper + '&nbsp;&nbsp;&nbsp;';
	}

	//格式化价格
	function formatPrice(value, row){
		var tempValue = value + '';
		if(tempValue.indexOf(".") > 0){
			var arr = tempValue.split(".");
			if(arr[1].length == 1){
				tempValue = tempValue + "0";
			}else if(arr[1].length > 2){
				tempValue = arr[0] + '.' + arr[1].substr(0, 2);
			}
		}else{
			tempValue = tempValue + ".00";
		}
		return tempValue;
	}

	//准备导出数据
	function readyExport(){
		$('#recExport').dialog({  
			title: '导出数据到Excel',  
			width: 200,
			height: 180,
			closed: false,  
			cache: false,   
			modal: true
		});
	}

	function exeExport(){
		var exportType = $("input[name='exportType']:checked").val() 
		
		var tids = '';
		var kcname = '';
		var usercompany = '';
		
		if(exportType == 1){
			var checkedItems = datagrid.datagrid('getChecked');
			if(checkedItems.length == 0){
				$.messager.alert('提示', '<br>您没有选中任何数据。', 'info');
				return;
			}
			$.each(checkedItems, function(index, item){
				if(tids.length > 0){tids = tids + ',';}
				tids = tids + "'" + item.tid + "'";
			});
		}else if(exportType == 2){	
			var rowsItems = datagrid.datagrid('getRows');
			if(rowsItems.length == 0){
				$.messager.alert('提示', '<br>当前页没有任何数据。', 'info');
				return;
			}
			$.each(rowsItems, function(index, row){
				if(tids.length > 0){tids = tids + ',';}
				tids = tids + "'" +row.tid + "'";
			});
		}else if(exportType == 3){
			var queryParams = datagrid.datagrid('options').queryParams;
			kcname = queryParams.kcname;
			usercompany = queryParams.usercompany;
		}else{
			$.messager.alert('提示', '<br>请选择导出Excel方式。', 'info');
			return;
		}

	    var form = $('<form></form>');  
	    // 设置属性  
	    form.attr('action', url + '?method=exportKcExcel&treeid=<%=treeid%>&islive=Y');  
	    form.attr('method', 'post');  
	    form.attr('target', '_self');  
	    // 创建Input  
	    var tidsInput = $('<input type="text" name="tids"/>');  
	    tidsInput.attr('value', tids);  
	    var kcnameInput = $('<input type="text" name="kcname"/>');  
	    kcnameInput.attr('value', kcname);  
	    var usercompanyInput = $('<input type="text" name="usercompany"/>');  
	    usercompanyInput.attr('value', usercompany);  

	    form.append(tidsInput);   
	    form.append(kcnameInput);  
	    form.append(usercompanyInput);  

	    form.appendTo("body") 

	    form.submit();  
	}
	</script>

	<div data-options="region:'center',title:'库存明细管理'">
	
	<!-- 表格面板 -->
	<table id="datagrid"></table>
	
	<!-- 新增或编辑面板 -->
	<div id="recSaveOrUpdate" class="easyui-dialog" closed="true" data-options="buttons:'#buttonsSaveOrUpdate'" style="padding-top:10px;overflow:hidden">
	    <form id="recSaveOrUpdateForm" name="recSaveOrUpdateForm" action="" method="post">
	    	<input type="hidden" id="tid" name="tid" value="">
	    	<table border="0" bordercolor="red">
	    		<tr height="30px">
	    			<td width="60px" align="right">库存名称</td>
	    			<td width="60px" colspan="5"><input style="width:326px" class="easyui-validatebox" type="text" id="kcname" name="kcname" data-options="validType:['length[0,100]']"/></td>
	    		</tr>
	    		
	    		<tr height="30px">
	    			<td align="right">单价</td>
	    			<td><input onBlur="javascript:toJSForKc()" style="width:80px" class="easyui-numberbox" type="text" id="price" name="price" data-options="precision:2,min:0.00,max:9999999999.99" value="0.00"/></td>
	    			<td align="right">数量</td>
	    			<td><input onBlur="javascript:toJSForKc()" style="width:80px" class="easyui-numberbox" type="text" id="amount" name="amount" data-options="precision:2,min:0.00,max:9999999999.99" value="0.00"/></td>
	    			<td align="right">合计</td>
	    			<td><input style="width:80px;background-color:#C0C0C0" class="easyui-validatebox" type="text" id="totalprice" name="totalprice" readOnly value="0.00"/></td>
	    		</tr>
	    		<tr height="30px">
	    			<td align="right">使用客户</td>
	    			<td colspan="5"><input style="width:326px" class="easyui-validatebox" type="text" id="usercompany" name="usercompany" data-options="validType:['length[0,100]']"/></td>
	    		</tr>
	    		<tr height="30px">
	    			<td align="right">备注</td>
	    			<td colspan="5"><input style="width:326px" class="easyui-validatebox" type="text" id="remark" name="remark" data-options="validType:['length[0,2000]']"/></td>
	    		</tr>
	    	</table>
	    </form>
	</div>
	<div id="buttonsSaveOrUpdate" style="display:none">
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:doSave(false)">保存</a>
		<span id="saveAndGoon">
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:doSave(true)">保存并继续新增</a>
		</span>
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#recSaveOrUpdate').dialog('close');">关闭</a>
	</div>
	
	<!-- 导出面板 -->
	<div id="recExport" class="easyui-dialog" closed="true" data-options="buttons:'#buttonsInvExport'" style="padding-top:10px;overflow:hidden">
	    	<table border="0" bordercolor="red">
				<tr height="25px">
	    			<td style="padding-left:20px"><input type="radio" id="" name="exportType" value="1"/></td><td style="padding-left:5px">导出选中数据</td>
	    		</tr>
	    		<tr height="25px">
	    			<td style="padding-left:20px"><input type="radio" id="" name="exportType" value="2"/></td><td style="padding-left:5px">导出当前页数据</td>
	    		</tr>
	    		<tr height="25px">
	    			<td style="padding-left:20px"><input type="radio" id="" name="exportType" value="3"/></td><td style="padding-left:5px">导出所有数据</td>
	    		</tr>
	    	</table>
	</div>
	<div id="buttonsInvExport" style="display:none">
		<a href="javascript:exeExport();" class="easyui-linkbutton">导出</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#recExport').dialog('close');">取消</a>
	</div>
	
	<!-- 增，删，改，查面板 -->
	<div id="tb" style="padding:0px;height:auto">
		<table width="100%" border="0" bordercolor="red">
			<tr>
				<td style="padding-right:0px">
					<%if(users.getKcAuth().indexOf("AUTH_A") >= 0){
					%>
					<a href="javascript:readySave();" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a>
					<%
					}else{
					%>
					<a href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'" style="color:#C0C0C0">新增</a>
					<%	
					}%>
				</td>
				<td width="50px" style="padding-left:0px">库存名称</td>
				<td width="90px"><input id="kcname" name="kcname" class="easyui-validatebox" style="width:80px;height:20px"/></td>
				<td width="50px" style="padding-left:0px">使用客户</td>
				<td width="90px">
					<input id="usercompany" name="usercompany" class="easyui-validatebox" style="width:80px;height:20px"/>
				</td>
				<td width="80px" style="padding-left:0px">
					<a href="javascript:doQuery();" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">查询</a>
				</td>								
			</tr>
		</table>
	</div>
	
	
	</div>
	<!-- 详细信息面板 -->
	<div data-options="region:'south',border:false" style="height:29px;background:#D8D8D8;padding:0px;">
		<table width="100%" border="0" bordercolor="red">
			<tr height="25px">
				<td width="9%" bgcolor="#CCDDFF" align="right">合计：</td>
				<td width="91%" colspan="3" bgcolor="#F8F8F8"><span id="sumDatagrid"></span></td>				
			</tr>
		</table>
	</div>
  </body>
</html>
